import { history } from 'umi';
import React, { useState, useRef, useEffect, useImperativeHandle } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Tag,
  Select,
  Descriptions,
  Form,
} from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table'
import { getModels, getModelVersions } from '../../CentralInference/service';
import format from '@/utils/format';
import trans from '@/utils/translate';

export type TableListItem = {
  name: string;
  engin: string;
  versionCount: string;
  source: string;
  createdAt: string;
  task: string;
  field: string;
}

interface Props {
  setSource: (s: string) => void;
}

const ImagePull: React.FC<Props> = (props, ref) => {
  const tableRef = useRef();
  const [show, setShow] = useState(false);
  const [rowKeys, setRowKeys] = useState([]);
  const [rows, setRows] = useState([]);
  const [versions, setVersions] = useState([]);
  const [nowModel, setNowModel] = useState({});
  useImperativeHandle(ref, () => ({
    open: () => {
      try {
        tableRef.current?.reload()
      } catch {
        console.log('old')
      }
      setShow(true);
    },
    close: () => {
      setShow(false);
      setVersions([])
      setRows([])
    },
  }));

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
      width: 250,
      render: (text) => (
        <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
          {text}
        </div>
      )
    },
    {
      title: '模型类型',
      dataIndex: 'engin',
      key: 'engin',
      render: (text, row) => {
        return <span>{row.task}-{row.field}</span>
      }
    },
    { title: '版本数', dataIndex: 'versionCount', key: 'versionCount' },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      render: (text) => trans(`model.source.${text}`)
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => format(text),
    },
  ];
  const versionColumns = [
    { title: '版本', dataIndex: 'name', key: 'name' },
    {
      title: '容器镜像',
      dataIndex: 'engine',
      key: 'engine',

    },
    { title: '网络结构', dataIndex: 'backbone', key: 'backbone' },
    { title: '数据集名称', dataIndex: 'datasetName', key: 'datasetName' },
    {
      title: '更新时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => format(text),
    },
  ];

  const switch_line = async (switch_type, i) => {
    console.log(i.source);
    props.setSource(i.source); // 设置用户选择的模型来源
    let key = i.key;
    let open_keys = rowKeys;
    setNowModel(i)
    if (switch_type) {
      getModelVersions(i.id, { pageNum: 1, pageSize: 40 }).then((res) => {
        if (res.code == 0) {
          setVersions(res.data.items);
        }
      });
      open_keys = [i.key];
    } else {
      open_keys = [];
      setVersions([]);
    }
    setRowKeys(open_keys);
  };
  function RenderTable(record: string) {
    return (
      <Table
        columns={versionColumns}
        dataSource={versions}
        pagination={{ hideOnSinglePage: true }}
        onRow={(record) => {
          return {
            onClick: (event) => {
              console.log(record);
              // props.setSource(record.source);
              const model = nowModel
              const version = record
              const info = {
                modelName: model.name,
                modelTask: `${model.task}-${model.field}`,
                version: version.name,
                engine: version.engine,
                datasetName: version.datasetName,
                updateTime: version.createdAt,
                device: version.device,
                id: model.id,
                versionId: version.versionId
              }
              props.selectVersion(info);
              ref.current.close();
            }, // 点击行
          };
        }}
      />
    );
  }

  return (
    <div>
      <Modal
        title="选择模型"
        visible={show}
        footer={null}
        width="900px"
        onCancel={() => {
          setShow(false);
        }}
      >
        <ProTable
          search={false}
          options={false}
          actionRef={tableRef}
          columns={columns}
          expandable={{
            expandedRowRender: RenderTable,
            expandedRowKeys: rowKeys,
            expandIcon: false,
            onExpand: switch_line,
          }}
          request={async (params, sorter, filter) => {
            const res = await getModels({
              pageNum: params.current,
              pageSize: params.pageSize,
            }).then((res) => {
              if (res.code === 0) {
                let items = res.data.items;
                items.map((e: any, index: number) => {
                  e.versions = [];
                  e.key = index;
                });
                setRows(items);
                return Promise.resolve({
                  data: rows,
                  total: res.data.total,
                  success: true,
                });
              }
            });
          }}
          dataSource={rows}
        />
      </Modal>
    </div>
  );
};
const FImagePull = React.forwardRef(ImagePull);
export default FImagePull;
